package com.gxyk.utils;

import java.util.Calendar;

import com.example.jiemian.R;
import com.gxyk.view.CityPickerDialog;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.text.TextUtils;
import android.util.SparseArray;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.TextView;
import android.widget.DatePicker.OnDateChangedListener;

public class DialogUtil {

	public final static int LOADING_ID = 0x01;
	private static SparseArray<Dialog> mManagerDialog;
	/**
	 * 锟�?涓寜閽殑 button id
	 */
	private static int oneButtonId = 10086;
	/**
	 * 涓や釜鎸夐挳鐨刡utton id
	 */
	private static int twoButtonId = 10001;
	/**
	 * 鍩庡競閫夋嫨妗嗙殑 id
	 */
	private static int citySelectId = 10010;
	/**
	 * 鏃堕棿閫夋嫨锟�? id
	 */
	private static int timeSelectId = 12121;
	@SuppressWarnings("unused")
	private static int timeSelectId2 = 12222;
	/**
	 * 杩涘害妗嗙殑 id
	 */
	private static int loadingId = 1234567;
	/*** 鎻愮幇寮瑰嚭妗嗙殑瀵嗙爜 **/
	private static int TixianId = 321123;

	private static NumberPicker radius_picker;
	private static TextView dismiss;
	private static TextView save;
	private static LinearLayout layout;
	/**
	 * 搴曢儴閫夋嫨锟�?
	 * 
	 * @param context
	 * @param title
	 *            鏍囬(鍙拷??)
	 * @param args
	 *            item鍐呭
	 * @param colorid
	 *            item瀛椾綋棰滆壊(鍙拷??)
	 * @param onClickListener
	 *            item鐐瑰嚮浜嬩欢(榛樿鎶婂唴瀹硅缃负view鐨則ag,鍙粠view.getTag()鍙栧嚭)
	 */
	public static void showSelectDialog(Context context, String title,
			String[] args, int colorid, final OnClickListener onClickListener) {
		final Dialog dlg = new Dialog(context, R.style.Dialog_Transparent_Theme);
		OnClickListener listener = new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (onClickListener != null) {
					onClickListener.onClick(arg0);
				}
				dlg.dismiss();
			}
		};
		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		LinearLayout layout = (LinearLayout) inflater.inflate(
				R.layout.dialog_bottom_select_view, null);
		final int cFullFillWidth = 10000;
		layout.setMinimumWidth(cFullFillWidth);
		LinearLayout contentList = (LinearLayout) layout
				.findViewById(R.id.dialogContent);
		Button cancel = (Button) layout.findViewById(R.id.dialogCancelBtn);
		TextView titleTv = (TextView) layout.findViewById(R.id.dialogTitle);
		View titleDivider = layout.findViewById(R.id.dialogTitleDivider);
		if (!TextUtils.isEmpty(title)) {
			titleTv.setText(title);
			titleTv.setVisibility(View.VISIBLE);
			titleDivider.setVisibility(View.VISIBLE);
		}
		cancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				dlg.dismiss();
			}
		});
		float density = getDensity(context);
		int height = (int) (density * 45);
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT, height);
		LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT, 1);
		for (int i = 0; i < args.length; i++) {
			String text = args[i];
			ImageView iv = new ImageView(context);
			iv.setBackgroundResource(R.color.line_gray);
			iv.setLayoutParams(params2);
			TextView btn = new TextView(context);
			btn.setGravity(Gravity.CENTER);
			btn.setText(text);
			btn.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
			btn.setBackgroundResource(R.drawable.bg_listitem_selector);
			if (colorid <= 0) {
				colorid = R.color.gray;
			}
			btn.setTextColor(context.getResources().getColor(colorid));
			btn.setTag(text);
			btn.setOnClickListener(listener);
			btn.setLayoutParams(params);
			if (i == 0) {
				contentList.addView(btn);
			} else {
				contentList.addView(iv);
				contentList.addView(btn);
			}
		}

		Window w = dlg.getWindow();
		WindowManager.LayoutParams lp = w.getAttributes();
		lp.x = 0;
		final int cMakeBottom = -1000;
		lp.y = cMakeBottom;
		lp.gravity = Gravity.BOTTOM;
		dlg.onWindowAttributesChanged(lp);
		dlg.setCanceledOnTouchOutside(true);
		dlg.setContentView(layout);
		dlg.show();
	}	

	private static IllegalArgumentException missingDialog(int id) {
		return new IllegalArgumentException("no dialog with id " + id
				+ " was ever " + "shown via Activity#showDialog");
	}

	public static float getDensity(Context context) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return scale;
	}
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	public static void showCityDialog(Context context, final String[] city,
			final TextView textView) {
		if (mManagerDialog == null) {
			mManagerDialog = new SparseArray<Dialog>();
		}
		Dialog dlg = (Dialog) mManagerDialog.get(citySelectId);
		if (dlg == null) {
			dlg = new Dialog(context, R.style.Dialog_Transparent_Theme);

			LayoutInflater inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			layout = (LinearLayout) inflater.inflate(R.layout.radius_diaog,
					null);
			final int cFullFillWidth = 10000;
			layout.setMinimumWidth(cFullFillWidth);
			dlg.setCanceledOnTouchOutside(false);
			mManagerDialog.put(citySelectId, dlg);
			radius_picker = (NumberPicker) layout
					.findViewById(R.id.radius_picker);
			radius_picker
					.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
			dismiss = (TextView) layout.findViewById(R.id.dismiss);
			save = (TextView) layout.findViewById(R.id.save);
		}

		radius_picker.setDisplayedValues(city);
		radius_picker.setMinValue(0);
		radius_picker.setMaxValue(city.length - 1);
		dismiss.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				dismissDialog(citySelectId);
			}
		});
		save.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				textView.setText(city[radius_picker.getValue()].toString());
				dismissDialog(citySelectId);
			}
		});
		Window w = dlg.getWindow();
		WindowManager.LayoutParams lp = w.getAttributes();
		lp.x = 0;
		final int cMakeBottom = -1000;
		lp.y = cMakeBottom;
		lp.gravity = Gravity.BOTTOM;
		dlg.onWindowAttributesChanged(lp);
		dlg.setCanceledOnTouchOutside(true);
		dlg.setContentView(layout);

		if (dlg.isShowing()) {
			dlg.dismiss();
		}
		dlg.show();

	}
	/**
	 * 取消进度�?
	 * 
	 * @param id
	 *            对话框唯�?id,对应某一个展示对话框方法
	 */
	public static void dismissDialog(int id) {
		try {
			if (mManagerDialog == null) {
				throw missingDialog(id);
			}
			Dialog dialog = mManagerDialog.get(id);
			if (dialog == null) {
				throw missingDialog(id);
			}
			dialog.dismiss();
			mManagerDialog.remove(id);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 时间底部选择dialog类似iOS
	 * 
	 * @author 文仲
	 * */
	public static void showTimeDialog(Context context, final TextView textView) {
		if (mManagerDialog == null) {
			mManagerDialog = new SparseArray<Dialog>();
		}
		Dialog dlg = (Dialog) mManagerDialog.get(timeSelectId);
		if (dlg == null) {
			dlg = new Dialog(context, R.style.Dialog_Transparent_Theme);
			LayoutInflater inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			LinearLayout layout = (LinearLayout) inflater.inflate(
					R.layout.time_dialog, null);
			final int cFullFillWidth = 10000;
			layout.setMinimumWidth(cFullFillWidth);
			dlg.setCanceledOnTouchOutside(false);
			mManagerDialog.put(timeSelectId, dlg);
			final DatePicker dialogView = (DatePicker) layout
					.findViewById(R.id.calendar_view);
			dialogView
					.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
			final TextView dismiss = (TextView) layout
					.findViewById(R.id.dismiss);
			final TextView save = (TextView) layout.findViewById(R.id.save);

			dialogView.init(dialogView.getYear(), dialogView.getMonth(),
					dialogView.getDayOfMonth(), new OnDateChangedListener() {
						@Override
						public void onDateChanged(DatePicker view,
								final int year, final int monthOfYear,
								final int dayOfMonth) {
							save.setOnClickListener(new OnClickListener() {

								@Override
								public void onClick(View arg0) {
									StringBuffer sb = new StringBuffer();
									sb.append(year + "-");
									if ((monthOfYear + 1) < 10) {
										sb.append("0" + (monthOfYear + 1) + "-");
									} else {
										sb.append((monthOfYear + 1) + "-");
									}
									if (dayOfMonth < 10) {
										sb.append("0" + dayOfMonth);
									} else {
										sb.append(dayOfMonth);
									}
									textView.setText(sb.toString());
									dismissDialog(timeSelectId);
								}
							});
						}
					});
			dismiss.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					dismissDialog(timeSelectId);
				}
			});
			save.setOnClickListener(new OnClickListener() {

				@SuppressWarnings("unused")
				@Override
				public void onClick(View arg0) {
					Calendar c = Calendar.getInstance();
					String selecterTime = c.get(Calendar.YEAR) + "-"
							+ (c.get(Calendar.MONTH) + 1) + " - "
							+ c.get(Calendar.DAY_OF_MONTH);
					StringBuffer sb = new StringBuffer();
					sb.append(c.get(Calendar.YEAR) + "-");
					if ((c.get(Calendar.MONTH) + 1) < 10) {
						sb.append("0" + (c.get(Calendar.MONTH) + 1) + "-");
					} else {
						sb.append(c.get(Calendar.MONTH) + 1 + "-");
					}
					if (c.get(Calendar.DAY_OF_MONTH) < 10) {
						sb.append("0" + c.get(Calendar.DAY_OF_MONTH));
					} else {
						sb.append(c.get(Calendar.DAY_OF_MONTH));
					}
					textView.setText(sb.toString());
					dismissDialog(timeSelectId);

				}
			});
			Window w = dlg.getWindow();
			WindowManager.LayoutParams lp = w.getAttributes();
			lp.x = 0;
			final int cMakeBottom = -1000;
			lp.y = cMakeBottom;
			lp.gravity = Gravity.BOTTOM;
			dlg.onWindowAttributesChanged(lp);
			dlg.setCanceledOnTouchOutside(true);
			dlg.setContentView(layout);
		}
		if (dlg.isShowing()) {
			dlg.dismiss();
		}
		dlg.show();

	}
	/**
	 * 城市底部选择dialog类似iOS
	 * 
	 * @author 文仲
	 * */

	public static CityPickerDialog showCityDialog(Activity activity,
			WindowManager windowManager, final TextView textView) {

		final CityPickerDialog mDialog = new CityPickerDialog(activity,
				R.style.Dialog_Transparent_Theme, textView);
		dialogBottom(mDialog, windowManager);

		return mDialog;
	}
	/**
	 * 控制dialog显示在底部
	 * */
	@SuppressWarnings("deprecation")
	private static void dialogBottom(Dialog mDialog, WindowManager windowManager) {
		Window window = mDialog.getWindow();
		window.setGravity(Gravity.BOTTOM);
		mDialog.setCanceledOnTouchOutside(false);// 设置点击Dialog外部任意区域关闭Dialog
		mDialog.show();

		Display display = windowManager.getDefaultDisplay();
		WindowManager.LayoutParams lp = mDialog.getWindow().getAttributes();
		lp.width = (int) (display.getWidth()); // 设置宽度
		mDialog.getWindow().setAttributes(lp);
	}
	/**
	 * 加载进度�?
	 * 
	 * @param context
	 * @param id
	 * @return
	 */
	public static Dialog showLoadDialog(Context context) {
		return showLoadDialog(context, loadingId, true);
	}
	/**
	 * 网络加载loading...
	 * @param context
	 * @param id
	 * @param isCancelable
	 * @return
	 */
	public static Dialog showLoadDialog(Context context, int id,
			boolean isCancelable) {
		if (mManagerDialog == null) {
			mManagerDialog = new SparseArray<Dialog>();
		}
		Dialog mDialog = mManagerDialog.get(id);
		if (mDialog != null) {
			if (mDialog.isShowing()) {
				mDialog.dismiss();
			}
			mManagerDialog.remove(id);
			mDialog = null;
		}
		mDialog = new Dialog(context, R.style.Dialog_Transparent_Theme);
		mDialog.setContentView(R.layout.loaddialog);
		mDialog.setCanceledOnTouchOutside(false);
		mDialog.setCancelable(isCancelable);
		mManagerDialog.put(id, mDialog);
		mDialog.show();
		return mDialog;
	}

	public static void dismissLoadDialog(){
		dismissDialog(loadingId);
	}	
}
